import 'package:flutter_module/common/base/page/BasePage.dart';
import 'package:flutter_module/common/base/page/BasicPage.dart';
import 'package:flutter_module/common/utils/date_util.dart';
import 'package:flutter_module/common/utils/dialog_util.dart';
import 'package:flutter_module/common/widgets/CommonWidget.dart';
import 'package:flutter_module/common/widgets/title_bar.dart';
import 'package:flutter_module/model/invite_record.dart';
import 'package:flutter_module/page/apply/history/apply_history_logic.dart';
import 'package:flutter_module/res/image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import '../../../res/colors.dart';

/// 申请记录统计页面
class ApplyHistoryPage extends BasePage {
  final ApplyHistoryLogic currentLogic = Get.put(ApplyHistoryLogic());

  /// 企业邀约人数
  final String applyCount;

  ApplyHistoryPage({super.key, required this.applyCount});

  @override
  State<ApplyHistoryPage> createState() => _ApplyHistoryPageState();
}

class _ApplyHistoryPageState
    extends BasicPage<ApplyHistoryPage, ApplyHistoryLogic> {
  @override
  Widget body(BuildContext context) {
    // 状态栏高度
    double statusHeight = MediaQuery.of(context).padding.top;
    // 头部高度
    double topHeight = 252;
    // 自定义导航栏高度
    double titleBarHeight = 56;
    return Column(
      children: [
        Stack(
          children: [
            // 头部背景图
            SvgPicture.asset(
              YouthImages.applyHistory_HeaderBGImage,
              width: MediaQuery.of(context).size.width,
            ),
            // 头部背景,
            Container(
              margin: EdgeInsets.only(top: titleBarHeight + statusHeight),
              child: _buildTopInfo(
                  topHeight - titleBarHeight - statusHeight, context),
            ),
          ],
        ),
        //申请列表头
        _buildListHeader(),
        //列表
        Expanded(child: _buildList()),
      ],
    );
  }

  @override
  ApplyHistoryLogic get currentLogic => widget.currentLogic;

  @override
  String screenName() {
    return "";
  }

  @override
  bool extendBodyBehindAppBar() {
    return true;
  }

  @override
  PreferredSizeWidget? appbar() {
    return const TitleBar(
      title: "申请记录统计",
      backgroundColor: Colors.transparent,
      mainColor: Colors.white,
      actions: [Text("")],
    );
  }


  // 头部处理按钮
  Widget _buildTopInfo(double topHeight,BuildContext context) {
    return SizedBox(
      height: topHeight,
      child: Stack(children: [
        // 邀约活动选择按钮容器
        _buildSelectedAct(context),
        // 今日 / 本周 / 本月 / 累计 按钮容器
        _buildDayType(),
        //邀约申请人数
        _buildInviteCount()
      ]),
    );
  }

  /// 今日 本周等tab
  Widget _buildDayType() {
    return Obx(() {
      return Container(
        margin: const EdgeInsets.only(
          left: 20,
          top: 24 + 24,
          right: 20,
        ),
        alignment: Alignment.center,
        // 设置均分容器
        child: Column(
          children: <Widget>[
            Row(
              // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                _buildTypeButton(1, '今日'),
                _buildTypeButton(2, '本周'),
                _buildTypeButton(3, '本月'),
                _buildTypeButton(4, '累计'),
              ],
            ),
          ],
        ),
      );
    });
  }

  /// 邀约申请人数
  Widget _buildInviteCount() {
    return Obx(() {
      return Container(
          margin: const EdgeInsets.only(top: 24 + 80),
          height: 30,
          alignment: Alignment.topCenter,
          // 申请人数 富文本
          child: RichText(
            textAlign: TextAlign.center,
            maxLines: 1,
            text: TextSpan(
              children: <TextSpan>[
                const TextSpan(
                  text: '申请人数：',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 17,
                      fontWeight: FontWeight.w500),
                ),
                TextSpan(
                  text: "${currentLogic.applyCount.value}",
                  style: const TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.w900),
                ),
                const TextSpan(
                  text: '人',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 17,
                      fontWeight: FontWeight.w500),
                )
              ],
            ),
          ));
    });
  }

  /// 当前选中活动的入口
  Widget _buildSelectedAct(BuildContext context) {
    //右边外间距
    double containerMarginRight = 16;
    //左边外间距
    double containerMarginLeft = 71;
    //水平方向内间距
    double containerPaddingH = 12;
    //右边图标的宽度
    double iconWidth = 14;

    //减去左右间距 , 最大宽度
    double containerMaxWidth = MediaQuery.of(context).size.width -
        containerMarginLeft -
        containerMarginRight;
    //减去左右内间距、右边图标的宽度、文字...预留距离10 , text最大宽度
    double textMaxWidth =
        containerMaxWidth - containerPaddingH * 2 - iconWidth - 10;
    return Row(
      textDirection: TextDirection.rtl,
      children: [
        GestureDetector(
          onTap: (){
            _selectActName(context);
          },
          child: Container(
            margin: EdgeInsets.only(right: containerMarginRight),
            constraints: BoxConstraints(maxWidth: containerMaxWidth),
            padding: EdgeInsets.symmetric(
                horizontal: containerPaddingH, vertical: 4),
            decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(24)),
                border:
                    Border.all(color: Colors.white, style: BorderStyle.solid)),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                    constraints: BoxConstraints(maxWidth: textMaxWidth),
                    child: Obx(() {
                      return Text(
                        currentLogic.selectedAct.value?.actName ?? '',
                        style: const TextStyle(color: Colors.white),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      );
                    })),
                SvgPicture.asset(
                  YouthImages.applyHistory_SelectApply,
                  width: iconWidth,
                  height: iconWidth,
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 选择活动
  void _selectActName(BuildContext context) {
    if (currentLogic.actNames != null) {
      List<String> actNames =
          currentLogic.actNames!.map((e) => e.actName ?? '').toList();
      DialogUtils.showItemSelectDialog(context,
          data: actNames,
          title: '活动',
          initialItem: currentLogic.selectedActPosition, onConfirm: (index) {
        currentLogic.changeAct(index);
      });
    }
  }

  // 创建 今日 / 本周 / 本月 / 累计 按钮
  Widget _buildTypeButton(int index, String title) {
    return Expanded(
      child: Stack(
        alignment: Alignment.center,
        children: [
          MaterialButton(
            onPressed: () {
              currentLogic.changeDayType(index);
            },
            child: Text(
              title,
              textAlign: TextAlign.center,
              maxLines: 1,
              style: const TextStyle(
                  fontSize: 14,
                  color: Colors.white,
                  fontWeight: FontWeight.w500),
            ),
          ),
          _buildTypeButtonIndicator(index)
        ],
      ),
    );
  }

  // 创建 今日 / 本周 / 本月 / 累计 底下指示器
  Widget _buildTypeButtonIndicator(int index) {
    return Container(
      margin: const EdgeInsets.only(top: 24),
      height: 2,
      width: 20,
      decoration: BoxDecoration(
          color: currentLogic.selectedType.value == index
              ? Colors.white
              : Colors.transparent,
          borderRadius: BorderRadius.circular(2),
          shape: BoxShape.rectangle),
    );
  }

  Widget _buildList() {
    return GetBuilder<ApplyHistoryLogic>(
      assignId: true,
      builder: (currentLogic) {
        if (currentLogic.inviteList.isEmpty) {
          return _buildEmpty();
        }
        return youthRefresher(
            refreshController: currentLogic.controller,
            child: ListView.builder(
              itemBuilder: (context, index) {
                return _buildListItem(currentLogic, index);
              },
              itemExtent: 46,
              itemCount: currentLogic.inviteList.length,
            ),
            onLoading: _onLoading);
      },
    );
  }

  /// 空数据页面
  Widget _buildEmpty() {
    return const Center(
      child: Text('暂无数据',
          style: TextStyle(fontSize: 16, color: YouthColors.color_333333)),
    );
  }

  /// 数据分页加载
  Future<void> _onLoading() async {
    currentLogic.fetchInviteRecord(isRefresh: false);
  }

  /// List item
  Widget _buildListItem(ApplyHistoryLogic currentLogic, int index) {
    if (currentLogic.inviteList.isEmpty) {
      return const SizedBox.shrink();
    }
    if (currentLogic.isSchoolType()) {
      return _buildSchoolItem(index);
    }
    return _buildOrgItem(index);
  }

  /// 学校列表item
  Widget _buildSchoolItem(int index) {
    InviteList invite = currentLogic.inviteList[index];

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(children: [
        //姓名
        _buildContentText(content: invite.userName ?? ''),
        //学号
        _buildContentText(content: invite.studentNumber ?? ''),
        //专业
        _buildContentText(content: invite.specialized ?? ''),
        //申请时间
        _buildContentText(
            content: invite.createTime != null
                ? DateUtil.formatDateMs(invite.createTime!,
                    format: DateFormats.y_mo_d2)
                : "",
            align: TextAlign.right),
      ]),
    );
  }

  /// 内容文本
  Widget _buildContentText(
      {required String content, TextAlign align = TextAlign.left}) {
    return Expanded(
      child: Text(
        content,
        style: const TextStyle(fontSize: 14, color: YouthColors.color_969699),
        textAlign: align,
        overflow: TextOverflow.ellipsis,
        maxLines: 1,
      ),
    );
  }

  /// 企业列表item
  Widget _buildOrgItem(int index) {
    InviteList invite = currentLogic.inviteList[index];
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 32),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            invite.userName ?? '',
            style:
                const TextStyle(fontSize: 14, color: YouthColors.color_333333),
          ),
          Text(
              invite.createTime != null
                  ? DateUtil.formatDateMs(invite.createTime!,
                      format: DateFormats.y_mo_d2)
                  : "",
              style: const TextStyle(
                  fontSize: 14, color: YouthColors.color_969699))
        ],
      ),
    );
  }

  Widget _buildListHeader() {
    return SizedBox(
      height: 100,
      child: Column(
        children: [
          Container(
            height: 50,
            padding: const EdgeInsets.only(left: 16),
            alignment: Alignment.centerLeft,
            child: const Text(
              '申请列表',
              style: TextStyle(color: YouthColors.color_333333, fontSize: 17),
            ),
          ),
          _buildListColumn()
        ],
      ),
    );
  }

  /// 列表头部列名
  Widget _buildListColumn() {
    return GetBuilder<ApplyHistoryLogic>(
      assignId: true,
      builder: (currentLogic) {
        if (currentLogic.inviteList.isEmpty == true) {
          return const SizedBox.shrink();
        }
        List<String> columnNames = currentLogic.isSchoolType()
            ? currentLogic.schoolColumns
            : currentLogic.orgColumns;
        return Container(
            padding: EdgeInsets.symmetric(
                horizontal: currentLogic.isSchoolType() ? 16 : 32),
            height: 50,
            color: YouthColors.color_ECF1F8,
            alignment: Alignment.center,
            child: Row(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: List.generate(columnNames.length, (index) {
                TextAlign align = TextAlign.left;
                if (index == columnNames.length - 1) {
                  align = TextAlign.right;
                }
                return Expanded(
                  child: Text(
                    columnNames[index],
                    style: const TextStyle(
                        color: YouthColors.color_7E7E80, fontSize: 14),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    textAlign: align,
                  ),
                );
              }),
            ));
      },
    );
  }
}
